<template>
  <div class="box">
    <div class="eva-con">
        <div class="left-menu">
          <div class="left-menu-top">
            <span>指标分类</span>
            <el-popover
              v-model:visible="ppVisible"
              placement="bottom-start"
              ref="ppLeftTop"
              trigger="click"
              width="300"
              @after-leave="ppCancel"
              >
              <template #reference>
                <span class="el-dropdown-link">
                  <button class="btn-color left-top-btn">新建分类</button>
                </span>
              </template>
                <el-row style="width: 300px">
                  <el-col>
                    <div style="font-weight: 800;color: rgb(106,104,115)">指标组名称</div>
                    <el-input
                      v-model="addEvaGroupTitle"
                      maxlength="15"
                      show-word-limit
                      type="text"
                      class="input-height"
                    />
                    <div style="font-size: 12px">仅支持数字、字母、减号、下划线和点</div>
                  </el-col>
                  <el-col style="margin-top: 15px">
                    <div style="font-weight: 800;color: rgb(106,104,115)">排序</div>
                    <el-input
                      v-model="addEvaGroupSort"
                      maxlength="3"
                      show-word-limit
                      type="text"
                      class="input-height"
                    />
                    <div style="font-size: 12px">在列表与考核详情中，按数字从大到小排序</div>
                  </el-col>
                  <el-col style="margin-top: 15px;padding-left:150px">
                    <el-button size="mini" class="close-btn" @click="ppCancel">取消</el-button>
                    <el-button size="mini" class="btn-color" @click="addOrUpdateEvaGroup()">确定</el-button>
                  </el-col>
                </el-row>
            </el-popover>
          </div>
          <el-scrollbar class="left-menu-con">
            <div 
              class="left-menu-item" 
              :class="{'left-menu-item-active': currentEva == index}" 
              v-for="(item,index) in evaGroup" 
              :key="item.group_id"
            >
              <div class="left-menu-item-con" @click="currentShowEva(index)">
                <i class="el-icon-folder"></i>
                <span class="left-menu-item-title">{{item.title}}</span>
                <span>({{item.count}})</span>
              </div>
              <div class="left-menu-icon">
                <el-dropdown>
                  <span class="el-dropdown-link">
                    <i class="el-icon-more cursor" style="font-size: 24px;"></i>
                    <el-icon class="el-icon--right">
                      <arrow-down />
                    </el-icon>
                  </span>
                  <template #dropdown>
                    <el-dropdown-menu class="left-menu-icon-dropdown">
                      <el-dropdown-item @click.native="updateEvaGroup(index)">编辑</el-dropdown-item>
                      <el-dropdown-item @click="deleteEvaGroup(item.id)">删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </el-scrollbar>
        </div>
        <div class="right-menu">
          <el-form class="elForm" :inline="true" :model="dataForm" :rules="dataRule" ref="dataForm">
            <el-form-item>
              <el-button
                  size="medium"
                  class="add-btn"
                  v-if="dataListSelections.length==0"
                  @click="addEvaItem()"
              >
                  新建指标
              </el-button>
              <el-button
                  size="medium"
                  v-if="dataListSelections.length!=0"
                  @click="moveEvaItem()"
              >
                  移动
              </el-button>
              <el-button
                  size="medium"
                  type="danger"
                  v-if="dataListSelections.length!=0"
                  @click="deleteEvaItem()"
              >
                  批量删除
              </el-button>
            </el-form-item>
            <el-form-item prop="examName">
              <el-input
                  v-model="dataForm.title"
                  placeholder="指标名称"
                  size="medium"
                  class="input"
                  clearable="clearable"
              />
              <el-button 
                class="search"
                size="small"
                @click="searchHandle()" 
                icon="el-icon-search"></el-button>
            </el-form-item>
          </el-form>
          <div class="right-menu-con">
            <el-table
              :data="tableData"
              border
              v-loading="dataListLoading"
              @selection-change="selectionChangeHandle"
              style="width: 100%;"
              size="medium"
              :header-cell-style="{borderColor: 'rgb(235,235,235)',background: 'rgb(247,247,247)'}"
              :cell-style="{padding: '8px 0',borderColor: 'rgb(235,235,235)'}"
              class="elTable"
              :row-key="getRowKeys"
              ref="table"
            >
              <el-table-column
                  type="selection"
                  :selectable="selectable"
                  header-align="center"
                  align="center"
                  width="50"
                  :reserve-selection="true"
              />
              <el-table-column prop="title" label="名称" />
              <el-table-column prop="type" label="评分类型" width="180" />
              <el-table-column prop="score" label="满分" width="80" />
              <el-table-column prop="creator" label="创建人" width="100" />
              <el-table-column width="60" label="操作" >
                <template #default="scope">
                  <el-dropdown>
                      <span class="el-dropdown-link">
                        <i class="el-icon-more cursor" style="font-size: 28px"></i>
                      </span>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item @click="moveEvaItem(scope.row.id)">移动</el-dropdown-item>
                          <el-dropdown-item @click="updateEvaItem(scope.row.id)">编辑</el-dropdown-item>
                          <el-dropdown-item @click="deleteEvaItem(scope.row.id)" :disabled="dataListSelections.length!=0">删除</el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                  </el-dropdown>
                </template>
              </el-table-column> 
            </el-table>
          </div>
          <!-- 分页 -->
          <el-pagination
            @size-change="sizeChangeHandle"
            @current-change="currentChangeHandle"
            :current-page="pageIndex"
            :page-sizes="[10, 20, 50]"
            :page-size="pageSize"
            :total="totalCount"
            layout="total, sizes, prev, pager, next, jumper"
          ></el-pagination>
        </div>
      </div>
    <!-- 新建指标弹框 -->
    <exam-eva-add ref="examEvaAdd" @refrashData="AddRefrashData"></exam-eva-add>
    <!-- 移动指标 -->
    <exam-eva-move v-if="moveVision" ref="examEvaMove" @refrashData="moveRefrashData"></exam-eva-move>
  </div>
</template>

<script>
import ExamEvaAdd from './ExamEvaAdd.vue'
import ExamEvaMove from './ExamEvaMove.vue'
export default {
  components: {
    ExamEvaAdd,
    ExamEvaMove
  },
  data() {
    return {
      dataListLoading: false,
      dataForm: {
        title: ''
      },
      tableData: [],
      allTemplate: [], // 考核模板内容
      dataListSelections: [],
      pageIndex: 1,
      pageSize: 10,
      totalCount: 0,
      // 指标组
      evaGroup: [],
      // 显示隐藏 弹出框
      ppVisible: false,
      // 新建指标组的名称
      addEvaGroupTitle: '',
      // 新建指标组的排序
      addEvaGroupSort: '',
      // 编辑功能 当前是哪个元素
      currentEvaGroup: -1,
      // 显示对应指标组的 指标
      currentEva: -1,
      // 显示移动弹窗
      moveVision: false,
      rules: {
        title:  [
          { required: true, message: '请输入考核名称', trigger: 'blur' },
        ],
      },
    }
  },
  created() {
    this.getEvaGroup() // 获取指标分类
    this.getEvaItem() // 获取指标项
  },
  methods: {
    // 提交给后端
    onSubmit() {
      let id = this.$route.params.id=='undefined' ? '' : this.$route.params.id
      // 指标内容
      let options = []
      // 总分
      let totalScore = 0
      this.evaGroup.forEach((item,index) => {
        let option = {}
        option.title = item.title
        option.sort = item.sort
        option.items = this.tableData[index]
        option.score = item.score
        options.push(option)
        totalScore += item.score
      })
      // 获取template_id
      let exam_rank_id
      for(let item of this.allTemplate) {
        if (item.title == this.form.template) {
          exam_rank_id = item.id
          break
        }
      }
      let data = {
        id,
        title: this.form.title,
        exam_rank_id,
        options,
        totalScore
      }
      // console.log(data);
      
      this.$http(`markTemplate/${id ? 'updateTemplate' : 'addTemplate'}`, 'post', data, false, resp => {
        if (resp.code == 200) {
          this.$message({
            message: '添加成功',
            type: 'success',
            duration: 1200
          })
          setTimeout(() => {
            this.$router.push({name: 'ExamTemp'})
          })
        }
      })
    },
    // 编辑前添加数据
    updateEvaGroup(index) {
      this.addEvaGroupTitle = this.evaGroup[index].title
      this.addEvaGroupSort = this.evaGroup[index].sort
      this.currentEvaGroup = index
      // 显示直接改变ppVisible 不行
      this.$refs.ppLeftTop.show()
    },
    // 左上角下拉框取消
    ppCancel() {
      this.addEvaGroupTitle = ''
      this.addEvaGroupSort = ''
      // this.$refs.ddLeftTop.$.hide()
      this.ppVisible = false
    },
    // 获取指标
    getEvaItem(search) {
      if (this.dataListSelections.length) {
        // 清除table选中
        this.$refs.table.clearSelection()
      }
      
      let data = {
        page: this.pageIndex,
        length: this.pageSize,
      }
      if (search) {
        data = {...data, ...search}
      }
      // console.log(data);
      
      this.$http('evaluation/selectEvaluationsBypages', 'post', data, false, resp => {
        if (resp.code == 200) {
          this.tableData = resp.page.list
          this.totalCount = resp.page.totalCount
          // console.log(resp.page);
        }
      })
    },
    // 添加指标
    addEvaItem() {
      this.$nextTick(() => {
        this.$refs.examEvaAdd.init()
      })
      // console.log(this.tableData);
      
    },
    // 添加指标弹窗回调
    AddRefrashData(dataObj) {
      // console.log(data);
      let {data} = dataObj
      let id = dataObj.id
      this.$http(`evaluation/${id ? 'updateEvaluations' : 'addEvaluations'}`, 'post', data, false, resp => {
        if (resp.code == 200) {
          this.currentShowEva(this.currentEva)
          this.getEvaGroup()
        }
      })
    },
    // 编辑指标
    updateEvaItem(id) {
      this.$nextTick(() => {
        this.$refs.examEvaAdd.init(id)
      })
    },
    // 移动指标
    moveEvaItem(id) {
      if (this.currentEva == -1) {
        this.$message({
          message: '请选择指标组',
          type: 'warning',
          duration: 1200
        })
      } else {
        let oldgroupId = this.evaGroup[this.currentEva].id
        let ids = id ? [id] : this.dataListSelections.map(item => item.id)
        let data = {
          oldgroupId,
          ids
        }
        this.moveVision = true
        this.$nextTick(() => {
          this.$refs.examEvaMove.init(data)
        })
      }
    },
    // 添加和编辑指标组 左上角下拉框确定
    addOrUpdateEvaGroup() {
      let index = this.currentEvaGroup
      if (index == -1) {
        console.log('add');
        // 增加
        if (this.addEvaGroupTitle != '') {
          let data = {
            title: this.addEvaGroupTitle,
            sort: this.addEvaGroupSort,
          }
          // console.log(data);
          
          this.$http('evaluation/addEvaluationGroup', 'post', data, false, resp => {
            if (resp.code == 200) {
              this.getEvaGroup()
            }
          })
          // 清空 + 隐藏
          this.ppCancel()
          // 取消选中的指标组
          this.currentEva = -1
        } else {
          this.$message({
            message: '请完善添加的信息',
            type: 'error',
            duration: 1200
          })
        }
      } else {
        console.log('update');
        
        // 修改
        let data = {
          groupId: this.evaGroup[index].group_id,
          title: this.addEvaGroupTitle,
          sort: this.addEvaGroupSort
        }
        // console.log(data);
        
        this.$http('evaluation/updateEvaluationGroup', 'post', data, false, resp => {
          if (resp.code == 200) {
            this.getEvaGroup()
          }
        })
        this.currentEvaGroup = -1
        // 清空 + 隐藏
        this.ppCancel()
      }
    },
    // 删除指标组
    deleteEvaGroup(id) {
      this.$confirm('确定要删除选中记录？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http('evaluation/deleteEvaluationGroup','post', {ids: [id]}, true, (resp) => {
          if (resp.code == 200) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duartion: 1200
            })
            // 清空table选中
            this.$refs.table.clearSelection()
            this.getEvaGroup()
            
          } else {
            this.$message({
              message: '未能删除记录',
              type: 'warning',
              duartion: 1200
            })
          }
        })
      })
    },
    // 获取指标分类
    getEvaGroup() {
      let data = {
        page: 1,
        length: 20
      }
      this.$http('evaluation/selectEvaluationGroup', 'post', data, false, resp => {
        if (resp.code == 200) {
          this.evaGroup = resp.page.list
          console.log(this.evaGroup);
        }
      })
    },
    // 删除指标
    deleteEvaItem(id) {
      let ids = id ? [id] : this.dataListSelections.map(item => item.id)
      
      this.$confirm('确定要删除选中记录？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http('evaluation/deleteEvaluations','post', {ids}, true, (resp) => {
          if (resp.code == 200) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duartion: 1200
            })
            this.getEvaGroup()
            this.currentShowEva(this.currentEva)
          } else {
            this.$message({
              message: '未能删除记录',
              type: 'warning',
              duartion: 1200
            })
          }
        })
      })
    },
    // 当前要显示的指标
    currentShowEva(index) {
      this.currentEva = index
      let search = {
        title: this.dataForm.title,
        groupId: this.evaGroup[index] ? this.evaGroup[index].id : null
      }
      console.log(search);
      
      this.getEvaItem(search)
    },
    // 显示从指标库添加指标
    showAddEvaHandle() {
      this.showAddEva = true
      this.$nextTick(() => {
        this.$refs.addEva.init()
			})
    },
    // move弹窗的回调
    moveRefrashData() {
      this.moveVision = false
      // console.log(this.currentEva);
      // 刷新页面
      this.currentShowEva(this.currentEva)
      this.getEvaGroup()
    },
    // 查询功能
		searchHandle() {
			this.$refs['dataForm'].validate(valid => {
				if (valid) {
          this.$refs['dataForm'].clearValidate()
          // 后端接收到''会报错，接收null是代表没有这个条件
					if(this.dataForm.title== '') {
            this.dataForm.title = null
          }
					if(this.pageIndex != 1) {
						this.pageIndex = 1
          }
          let search = {
            title: this.dataForm.title
          }
					this.getEvaItem(search)
				} else {
					return false
				}
			})
		},
    // 更新TableData里的指标数据 (添加指标的回调)
    updateTableData(data) {
      // console.log(data);
      data.forEach(item => {
        let f = true
        for (let item2 of this.tableData[this.currentEva]) {
          if (item2.id == item.id) {
            f = false
            break
          }
        }
        if (f) {
          this.tableData[this.currentEva].push(item)
        }
      });
      
      // 计算分数
      let sum = 0
      this.tableData[this.currentEva].forEach(item2 => {
        sum += item2.score
      })
      this.evaGroup[this.currentEva].score = sum
    },
    // 分页一页数量改变时触发
		sizeChangeHandle(val) {
			this.pageSize = val
			this.pageIndex = 1
			this.loadDataList()
		},
		// 分页换页时触发
		currentChangeHandle(val) {
			this.pageIndex = val
			this.loadDataList()
		},
    selectionChangeHandle: function(val) {
      this.dataListSelections = val;
    },
    selectable: function(row, index) {
      // console.log(row)
      if (row.systemic || row.users > 0) {
          return false;
      }
      return true;
    },
    // 保存选中的数据id,row-key就是要指定一个key标识这一行的数据
    getRowKeys(row) {
      return row.id
    },
  },
  computed: {

  }
}
</script>

<style lang="scss" scoped>
@import './examEva.scss';
</style>